
'use strict';

var joinButton = document.getElementById('joinButton');
var shareDeskButton = document.getElementById('shareDeskButton');
var exitButton = document.getElementById('exitButton');
var divConfig = document.getElementById('divConfig');
var divExtensionExist = document.getElementById('divExtensionExist');
var divExtensionInfo = document.getElementById('divExtensionInfo');

var defName = 'John-' + Math.random().toString(36).substr(2,4)
var myName = parseURL('myName', defName);
var confrId = parseURL('confrId', '000');
var xswitch_server_url = parseURL('xsw', '/xrtc-switch/');
var isOfferRole = false;
var videoInEnabled = true;
var videoOutEnabled = true;
var replace_ip_from = null;
var replace_ip_to = null;

// var xswitch_server_url = 'http://127.0.0.1:1880/rtc';
// var xswitch_server_url = 'http://121.41.87.159:1880/rtc'; // turn2 

// ping an
// var xswitch_server_url = 'http://video-pa.easemob.com/rtc';
// replace_ip_from = /215.128.35.8/g;
// replace_ip_to = "103.28.214.152";

// var xswitch_server_url = 'http://121.41.87.159:9999/rtc'; // turn2
// replace_ip_from = /121.41.87.159/g;
// replace_ip_to = "127.0.0.1";


console.log('myName=', myName);
console.log('confrId=', confrId);
console.log('xsw=', xswitch_server_url);
console.log('ip_from=', replace_ip_from);
console.log('ip_to=', replace_ip_to);

divConfig.innerHTML = '';
divConfig.innerHTML += 'myName: ['  + myName + ']' + '&nbsp&nbsp&nbsp&nbsp&nbsp';
divConfig.innerHTML += 'confrId: [' + confrId + ']' ;

var rtcStreams = new Array();

for (var i=0;i<4;i++){
  (function(){
    
    var s = {};
    s.name = 'rtcs-'+i;
    s.streamUId = null;

    var videoName = 'video'+i;
    s.video = document.getElementById(videoName);
    s.canvas = document.getElementById('canvas'+i);
    s.label = document.getElementById('label'+i);
    s.statiLabel = document.getElementById('stati'+i);
    s.videoCheck = document.getElementById('videoCheck'+i);
    s.audioCheck = document.getElementById('audioCheck'+i);

    rtcStreams[i] = s;

    s.label.innerHTML = "";
    s.video.addEventListener('loadedmetadata', function() {
      console.log(videoName + ' loadedmetadata: ' + s.video.videoWidth +' x ' + s.video.videoHeight);
    });

    s.video.onresize = function() {
      console.log(videoName + ' size changed to ' + s.video.videoWidth + 'x' + s.video.videoHeight);
    };
  })();
  
}


function getEmptyRTCS(streamUId){
  for(k in rtcStreams){
    var rtcs = rtcStreams[k];
    if(!rtcs.streamUId){
      rtcs.streamUId = streamUId;
      return rtcs;
    }
  }
  return null;
}

function findExistRTCS(streamUId){
  for(var k in rtcStreams){
    var rtcs = rtcStreams[k];
    if(rtcs.streamUId === streamUId){
      return rtcs;
    }
  }
  return null;
}

function returnRTCS(streamUId){
  for(k in rtcStreams){
    var rtcs = rtcStreams[k];
    if(rtcs.streamUId === streamUId){
      rtcs.streamUId = null;
      rtcs.label.innerHTML = '';
      rtcs.statiLabel.innerHTML = '';
      self.log('return rtcs: ', rtcs);
      return;
    }
  }
}

var confrListener = {

  onJoined: function(o, sessId){
    self = this;
    rtcStreams[0].label.innerHTML = myName;
    self.log('onJoined: sessId=', sessId);
  },

  onMemberAttended: function(o, sessId, memId){
    self = this;
    self.log('onMemberAttended: sessId=', sessId, ', memId=', memId);
  },

  onMemberLeave: function(o, sessId, memId){
    self = this;
    self.log('onMemberLeave: sessId=', sessId, ', memId=', memId);
  },

  onCustomEvent: function(o){
    
  },

  onStreamEvent: function(o, sessId, memId, streamId, sevent){
    self = this;
    self.log('onStreamEvent: sessId=', sessId, ',memId=', memId, ', streamId=', streamId, ', event=', sevent);
    if(memId === myName){
      var rtcs = findExistRTCS(streamId);
      self.log('my stream event ', sevent);
      if(rtcs){
        if(sevent === 'onStreamStartPublish'){
          rtcs.label.innerHTML = memId;
        }else{
          returnRTCS(streamId);
        }
      }else{
        self.log('unknown my stream, streamId=', streamId);  
      }
      return;
    }

    if(sevent === 'onStreamStartPublish'){
      var rtcs = getEmptyRTCS(streamId);
      if(!rtcs){
        self.log('subscribe streamId ', streamId, ', rtcs ', rtcs.name);
        return;
      }
      rtcs.label.innerHTML = memId;
      self.log('subscribe streamId ', streamId, ', rtcs ', rtcs.name);
      confrSession.subscribeStream(streamId, rtcs.video, rtcs.canvas);
    }else if(sevent === 'onStreamStopPublish'){
      returnRTCS(streamId);
    }
  },

  onExitd: function(o, sessId){
    self.log('onExitd');
    joinButton.disabled = false;
  },

  onError: function(o, sessId, msg){
    self = this;
    if(msg === 'kick'){
      alert('joined on other device');  
    }
    
  },

  onStreamStatistics: function(o, sessId, memId, streamId, stats){
    self = this;
    var rtcs = findExistRTCS(streamId);
    if(!rtcs) return;
    rtcs.statiLabel.innerHTML = '';

    var keys = ['a', 'v', 'sz'];
    for(var ki in keys){
      var k = keys[ki];
      if(stats[k]){
        rtcs.statiLabel.innerHTML += k + ':' + stats[k] + '&nbsp&nbsp&nbsp';
      }
    }
  },

  onShareDesktopEnable: function(enabled){
    if(shareDeskButton){
      shareDeskButton.disabled = !enabled;
    }
  },


  log: function(){
    var self = this;
    var arr = ['|user|'];
    for(var i = 0; i < arguments.length; i++){
      arr.push(arguments[i]);
    }
    console.log.apply(console, arr);
  }

};

var confrSession = null;
var myPublishId = myName+'-pub1';


if(joinButton){
  joinButton.onclick = function(){
    console.log('click joinButton');
    console.log('isOfferRole=', isOfferRole);
    joinButton.disabled = true;

    var ticket = {
      url: xswitch_server_url,
      userId: myName,
      confrId: confrId,
    };
    confrSession = new XConferenceSession();
    confrSession.setListener(confrListener);
    confrSession.joinConference(myName, myName+'-nick', ticket, myPublishId);
    var rtcs = rtcStreams[0];
    rtcs.streamUId = myPublishId;
    confrSession.setLocal(rtcs.video, rtcs.canvas);

  };  
}

if(shareDeskButton){
  // shareDeskButton.disabled = true;  
  shareDeskButton.onclick = function(){
    var streamId = 'desk1';
    var rtcs = getEmptyRTCS(streamId);
    if(!rtcs){
      self.log('get empty rtcs for desktop pub fail streamId ', streamId);
      return;
    }

    shareDeskButton.disabled = true;
    confrSession.publishDesktop('desk1', rtcs.video);
  }
}


if(exitButton){
  exitButton.onclick = function() {
    if(confrSession){
      confrSession.exitConference('normal');
    }
    joinButton.disabled = false;
    shareDeskButton.disabled = true;
  };
}

console.log('detecting extension...');
rsdListenEventLoaded(function(exist){
  console.log('extension exist=', exist);
  if(!exist){
    divExtensionExist.innerHTML = '未检测到共享桌面插件';  
    divExtensionInfo.style.display = null;
  }
});



function parseURL(name, defaultValue){  
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");  
  var r = window.location.search.substr(1).match(reg);  
  if(r!=null){
    return unescape(r[2]);
  } 
  return defaultValue;  
}







